//
//  TYGlobal.m
//  mana
//
//  Created by wbb on 2023/7/13.
//

#import "TYGlobal.h"

@implementation TYGlobal
+ (void)logout {
    [TYGlobal removeAllInfo];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate toLoginVC];
}
/// MARK:  删除NSUserDefaults所有记录
+ (void)removeAllInfo {
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
    
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"expiretime"]);
}
+ (BOOL)isLogin {
    NSString *token = [[NSUserDefaults standardUserDefaults] valueForKey:TY_TOKEN];
    if(token && token.length > 0) {
        return YES;
    }
    return NO;
}
//  颜色转换为背景图片
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 60.0f, 30.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}


+ (NSString *)ty_jsonStringforDic:(NSDictionary *)dic {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;

    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (CGFloat)widthForText:(NSString *)text textFont:(CGFloat)fontSize  standardHeight:(CGFloat)controlHeight
{
    if ([text length]==0) {
        return 0;
    }else {
        NSDictionary *attrbute = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
        return  [text boundingRectWithSize:CGSizeMake(1000,controlHeight) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrbute context:nil].size.width;
    }
}

+ (BOOL)isBlankString:(NSString *)string {
    if (string == nil || string == [NSNull null]) {
        return YES;
    }
    
    if (![string isKindOfClass:[NSString class]]) {
        return YES;
    }
    
    // 判断是否全为空格或空字符串
    NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return trimmedString.length == 0;
}


+ (NSArray<NSDate *> *)getYearTimeRange:(NSInteger)year {
    // 检查年份有效性（大于0且不超过当前年份+100）
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *currentComps = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger currentYear = currentComps.year;
    
    if (year <= 0 || year > currentYear + 100) {
        return nil;
    }
    
    // 获取日历实例并设置为公历
//    [calendar setCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    // 构建起始时间（YYYY-01-01 00:00:00）
    NSDateComponents *startComps = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
    startComps.year = year;
    startComps.month = 1;
    startComps.day = 1;
    startComps.hour = 0;
    startComps.minute = 0;
    startComps.second = 0;
    NSDate *startDate = [calendar dateFromComponents:startComps];
    
    // 构建结束时间
    NSDate *endDate;
    if (year < currentYear) {
        // 往年：截止到12月31日23:59:59
        NSDateComponents *endComps = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
        endComps.year = year;
        endComps.month = 12;
        endComps.day = 31;
        endComps.hour = 23;
        endComps.minute = 59;
        endComps.second = 59;
        endDate = [self getValidEndDate:endComps calendar:calendar];
    } else if (year == currentYear) {
        // 当年：截止到当前月份最后一天23:59:59
        NSDateComponents *currentMonthComps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:[NSDate date]];
        currentMonthComps.year = year;
        currentMonthComps.hour = 23;
        currentMonthComps.minute = 59;
        currentMonthComps.second = 59;
        
        // 获取当前月的最后一天
        NSRange dayRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[calendar dateFromComponents:currentMonthComps]];
        currentMonthComps.day = dayRange.length;
        endDate = [calendar dateFromComponents:currentMonthComps];
    } else {
        // 未来年份（year > currentYear）：返回空
        return nil;
    }
    
    return @[startDate, endDate];
}

+ (NSDate *)getValidEndDate:(NSDateComponents *)comps calendar:(NSCalendar *)calendar {
    // 检查12月31日是否有效，无效时获取当月最后一天
    NSDate *testDate = [calendar dateFromComponents:comps];
    if (testDate) {
        return testDate;
    } else {
        NSRange dayRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[calendar dateFromComponents:comps]];
        comps.day = dayRange.length;
        return [calendar dateFromComponents:comps];
    }
}
+ (NSArray *)timeRange:(NSInteger)year {
    /*NSInteger currentYear = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:[NSDate date]].year;*/
    NSArray<NSDate *> *currentRange = [TYGlobal getYearTimeRange:year];
    // 格式化日期输出
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 输出当前年份结果（截止到当月）
    if (currentRange) {
        NSString *start = [formatter stringFromDate:currentRange[0]];
        NSString *end = [formatter stringFromDate:currentRange[1]];
        NSLog(@"当前年份(%ld)范围: %@ 到 %@", (long)year, start, end);
//        [self nhtjRequestData:group startTime:start endTime:end];
        return @[start,end];
    }
    return @[];
}

@end
